/**
 * 
 */
package mdb.com.vn.web.beans;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import mdb.com.vn.model.Customer;
import mdb.com.vn.model.IBanking;
import mdb.com.vn.model.IBankingSms;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.TextUtil;
import mdb.com.vn.web.view.IBDataModel;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 * @author tu.dod
 *
 */
@ManagedBean(name = "iBankingBean")
@ViewScoped
public class IBankingBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String createdBy;
	private Date processDate;
	private Date processDateIbanking;

	private Date lastUpdated;
	private Date nextProcess;

	private StreamedContent file;
	private boolean btnVisible;
	private boolean btnSaveVisible;
	private boolean btnEnableGenerate;
	
	private List<IBanking> iBankings;
	private IBDataModel ibDataModel;
	private IBanking IBSelected;
	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;
	
	@PostConstruct
	public void init(){
		iBankings = new ArrayList<IBanking>();
		iBankings = mdbServices.getIBankingByStatus(TextUtil.PROCESSED);
		ibDataModel = new IBDataModel(iBankings);
		lastUpdated = mdbServices.getLastUpdatedLoans(TextUtil.IB_MODULE);
		nextProcess = DateUtils.nextMonth(lastUpdated, 1);
	}
	public void searchIBankingByDate(){
		if (processDate != null) {
			iBankings = mdbServices.getIBankingByStatus(TextUtil.PROCESSED, processDate);
			ibDataModel = new IBDataModel(iBankings);
		} else {
			iBankings = mdbServices.getIBankingByStatus(TextUtil.PROCESSED);
			ibDataModel = new IBDataModel(iBankings);
		}
	}
	public void generateLuckyDrawG2ForIB() {
		if (createdBy.equals("TUNG.NS")) {
			processDate = new Date();
			Date tempDte = processDate;
			try {
				if (DateUtils.compareDateNoTime(tempDte, lastUpdated) > 0) {
					mdbServices.addIBLuckyDrawG2ByScript(createdBy, processDateIbanking);
					iBankings = mdbServices.getIBankingByStatus(TextUtil.PROCESSED);
					ibDataModel = new IBDataModel(iBankings);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Đã cấp mã dự thưởng cho khách hàng", ""));
					
					lastUpdated = mdbServices.getLastUpdatedLoans(TextUtil.IB_MODULE);
					nextProcess = DateUtils.nextMonth(lastUpdated, 1);
					try {
						if (DateUtils.compareDateNoTime(new Date(), nextProcess) < 0 ){
							setBtnEnableGenerate(false);
						}else{
							setBtnEnableGenerate(true);
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else {
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Hệ thống đã được xử lý dữ liệu cho ngày "
											+ DateUtils.format(processDate, "dd/MM/yyyy"), ""));
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Giao dịch bị từ chối do bạn không có quyền",
							"Vui lòng liên hệ quản trị hệ thống"));
		}

	}
	
	public void transferDataToSendSMS(){
		try {
			for (IBanking iBanking : iBankings) {
				IBankingSms ibSmsTemp = null;
				ibSmsTemp = mdbServices.getIBSmsByID(iBanking.getId());
				if(ibSmsTemp == null){
					Customer customer = mdbServices.getCustomerInfos(iBanking.getCustomerId());
					String phone = "";
					String branch = "";
					if (customer != null) {
						phone = customer.getPhoneCountryCode() + "-"
								+ customer.getPhoneAreaCode() + "-"
								+ customer.getPhoneNumber();
						branch = customer.getBranchCode();
						
					} else {
						phone = "N/A";
						branch = "Anonymous";
					}
				
					IBankingSms bankingSms = new IBankingSms();
					bankingSms.setCreatedBy(iBanking.getCreatedBy());
					bankingSms.setCustomerId(iBanking.getCustomerId());
					bankingSms.setFinCycle(iBanking.getFinCycle());
					bankingSms.setId(iBanking.getId());
					bankingSms.setLkdNum(iBanking.getLkdNum());
					bankingSms.setPeriodCode(iBanking.getPeriodCode());
					bankingSms.setPhoneNum(phone);
					bankingSms.setProcessDate(iBanking.getProcessDate());
					bankingSms.setStatus(iBanking.getStatus());
					bankingSms.setTotalAmtTxn(iBanking.getTotalAmtTxn());
					bankingSms.setTotalCounterTxn(iBanking.getTotalCounterTxn());
					bankingSms.setBranchCode(branch);
					mdbServices.addIBSms(bankingSms);
				}
				
			}
			FacesContext
			.getCurrentInstance()
			.addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Chuyên dữ liệu thành công cho phép chi nhánh cập nhật số điện thoại",
							""));
			
		} catch (Exception e) {
			FacesContext
			.getCurrentInstance()
			.addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Đã cố xảy ra trong quá trình chuyển dữ liệu",
							"Vui lòng liên hệ quản trị để khác phục sự cố này"));
		}
		
	}
	
	public void createExcelIBByPoi(){
			Row row = null;
			Cell cell = null;
			try {
				Workbook wb = new HSSFWorkbook();
				HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
				HSSFFont fontHeader = (HSSFFont) wb.createFont();
				fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
				styleHeader.setFont(fontHeader);
				Sheet sheet = wb.createSheet("IBanking");
				row = sheet.createRow((short) 0);
				List<String> columnNames = new ArrayList<String>();

				columnNames.add("Số gcif");
				columnNames.add("Tên khách hàng");
				columnNames.add("Số điện thoại");
				columnNames.add("Ngày bắt đầu");
				columnNames.add("Ngày kết thúc");
				columnNames.add("Số tiền chuyển khoản IB");
				columnNames.add("Số lần giao dịch");
				columnNames.add("Tổng số mã dự thưởng");
				columnNames.add("Mã dự thưởng");
				columnNames.add("Điểm giao dịch");
				for (int i = 0; i < columnNames.size(); i++) {
					cell = row.createCell(i);
					cell.setCellValue(columnNames.get(i));
					cell.setCellStyle(styleHeader);
				}
				int j = 1;
				List<Object[]> tabularData = new ArrayList<Object[]>();
				for (IBanking iBanking : iBankings) {
					
					Customer customer = mdbServices.getCustomerInfos(
							iBanking.getCustomerId());
					String phone = "";
					String customerName = "";
					String companyName = "";
					if (customer != null){
						phone = customer.getPhoneCountryCode()+customer.getPhoneAreaCode()+customer.getPhoneNumber();
						customerName = customer.getCustomerName();
						companyName = mdbServices.getCompanyNameByCode(customer.getBranchCode());
					}else{
						phone = "N/A";
						customerName = "N/A";
						companyName = "N/A";
					}
					Calendar cal = Calendar.getInstance();
			        cal.setTime(iBanking.getProcessDate());
			        int month = cal.get(Calendar.MONTH);
			        int year = cal.get(Calendar.YEAR);
			        String dateFrom = "";
			        if(month == 11 && year == 2013){
			        	dateFrom = "09/12/2013"; 
			        }
			        if(month == 0 && year == 2014){
			        	dateFrom = "09/12/2013"; 
			        }
			        if(month == 1 && year == 2014){
			        	dateFrom = "10/01/2014";
			        }
			        if(month == 2 && year ==2014){
			        	dateFrom = "10/02/2014";
			        }
			        
					String lkd_num_g2 = mdbServices.getAllLuckyDrawG2Code(TextUtil.IB_MODULE,iBanking.getCustomerId(),iBanking.getProcessDate(), TextUtil.PROCESSED);
					tabularData
							.add(new Object[] {
									iBanking.getCustomerId(),
									customerName,
									phone,
									dateFrom,
									DateUtils.format(iBanking.getProcessDate(), "dd/MM/yyyy") ,
									iBanking.getTotalAmtTxn(),
									iBanking.getTotalCounterTxn(),
									iBanking.getLkdNum(),
									lkd_num_g2,
									companyName});
				}
				
				HSSFCellStyle styleRow = (HSSFCellStyle) wb
						.createCellStyle();
				HSSFFont fontRow = (HSSFFont) wb.createFont();
				fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
				styleRow.setFont(fontRow);
				
				for (Object[] temp : tabularData) {
					row = sheet.createRow((short) j);
					for (int k = 0; k < temp.length; k++) {
						cell = row.createCell(k);
						cell.setCellValue(temp[k].toString());
						cell.setCellStyle(styleRow);
					}
					j++;
				}
				tabularData = null;
				String excelFileName = "IB_REPORT.xls";
				FileOutputStream fos = new FileOutputStream(excelFileName);
				wb.write(fos);
				fos.flush();
				fos.close();
				InputStream stream = new BufferedInputStream(new FileInputStream(
						excelFileName));
				file = new DefaultStreamedContent(stream, "application/xls",
						excelFileName);
				setBtnVisible(true);
				FacesContext
						.getCurrentInstance()
						.addMessage(
								null,
								new FacesMessage(FacesMessage.SEVERITY_INFO,
										"Xử lý xuất dữ liệu thành công",
										"Vui lòng nhấn nút 'Tải về máy' để tại file excell về máy."));
			} catch (Exception e) {
				setBtnVisible(false);
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR,
								"Xử lý xuất dữ liệu thất bại",
								"Vui lòng liên hệ quản trị hệ thống."));
				e.printStackTrace();
			}

		
	}

	public void downloadPreventedIB(){
		file = null;
	}
	
	/**
	 * @return the createdBy
	 */
	public String getCreatedBy() {
		return createdBy;
	}
	/**
	 * @param createdBy the createdBy to set
	 */
	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}
	/**
	 * @return the processDate
	 */
	public Date getProcessDate() {
		return processDate;
	}
	/**
	 * @param processDate the processDate to set
	 */
	public void setProcessDate(Date processDate) {
		this.processDate = processDate;
	}
	/**
	 * @return the lastUpdated
	 */
	public Date getLastUpdated() {
		return lastUpdated;
	}
	/**
	 * @param lastUpdated the lastUpdated to set
	 */
	public void setLastUpdated(Date lastUpdated) {
		this.lastUpdated = lastUpdated;
	}
	/**
	 * @return the nextProcess
	 */
	public Date getNextProcess() {
		return nextProcess;
	}
	/**
	 * @param nextProcess the nextProcess to set
	 */
	public void setNextProcess(Date nextProcess) {
		this.nextProcess = nextProcess;
	}
	/**
	 * @return the btnVisible
	 */
	public boolean isBtnVisible() {
		return btnVisible;
	}
	/**
	 * @param btnVisible the btnVisible to set
	 */
	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}
	/**
	 * @return the btnSaveVisible
	 */
	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}
	/**
	 * @param btnSaveVisible the btnSaveVisible to set
	 */
	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}
	/**
	 * @return the iBankings
	 */
	public List<IBanking> getiBankings() {
		return iBankings;
	}
	/**
	 * @param iBankings the iBankings to set
	 */
	public void setiBankings(List<IBanking> iBankings) {
		this.iBankings = iBankings;
	}
	/**
	 * @return the iBSelected
	 */
	public IBanking getIBSelected() {
		return IBSelected;
	}
	/**
	 * @param iBSelected the iBSelected to set
	 */
	public void setIBSelected(IBanking iBSelected) {
		IBSelected = iBSelected;
	}
	/**
	 * @return the file
	 */
	public StreamedContent getFile() {
		return file;
	}
	/**
	 * @param mdbServices the mdbServices to set
	 */
	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}
	/**
	 * @return the ibDataModel
	 */
	public IBDataModel getIbDataModel() {
		return ibDataModel;
	}
	/**
	 * @return the btnEnableGenerate
	 */
	public boolean isBtnEnableGenerate() {
		return btnEnableGenerate;
	}
	/**
	 * @param btnEnableGenerate the btnEnableGenerate to set
	 */
	public void setBtnEnableGenerate(boolean btnEnableGenerate) {
		this.btnEnableGenerate = btnEnableGenerate;
	}
	/**
	 * @return the processDateIbanking
	 */
	public Date getProcessDateIbanking() {
		return processDateIbanking;
	}
	/**
	 * @param processDateIbanking the processDateIbanking to set
	 */
	public void setProcessDateIbanking(Date processDateIbanking) {
		this.processDateIbanking = processDateIbanking;
	}
	

}
